package com.bw.gmall.realtime.dwd.db.split.app;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.common.base.BaseApp;
import com.bw.gmall.realtime.common.constant.Constant;
import com.bw.gmall.realtime.common.util.DateFormatUtil;
import com.bw.gmall.realtime.common.util.FlinkSinkUtil;
import org.apache.doris.shaded.org.apache.arrow.flatbuf.DateUnit;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SideOutputDataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;

public class DwdBaseLog extends BaseApp {
    public static void main(String[] args) throws Exception {
        new DwdBaseLog().start(10011, 4, Constant.TOPIC_LOG, Constant.TOPIC_LOG);
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1.做数据清洗
        SingleOutputStreamOperator<JSONObject> etlStream = stream.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                try {
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    String ts = jsonObject.getString("ts");
                    JSONObject common = jsonObject.getJSONObject("common");
                    String mid = common.getString("mid");
                    if (ts != null && mid != null) {
                        collector.collect(jsonObject);
                    }
                } catch (Exception e) {
                }

            }
        });
        // 2.新来用户校验
        SingleOutputStreamOperator<JSONObject> wmStream = etlStream.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject jsonObject, long l) {
                return jsonObject.getLong("ts");
            }
        }));
        //为了同一个走一个并行度，必须KeyBy
        SingleOutputStreamOperator<JSONObject> isNewStream = wmStream.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject jsonObject) throws Exception {
                return jsonObject.getJSONObject("common").getString("mid");
            }
        }).process(new KeyedProcessFunction<String, JSONObject, JSONObject>() {
            ValueState<String> firstLogin;

            @Override
            public void open(Configuration parameters) throws Exception {
                firstLogin = getRuntimeContext().getState(new ValueStateDescriptor<String>("first_login", String.class));
            }

            @Override
            public void processElement(JSONObject jsonObject, KeyedProcessFunction<String, JSONObject, JSONObject>.Context context, Collector<JSONObject> collector) throws Exception {
                // 获取状态的值
                String value = firstLogin.value();
                Long ts = jsonObject.getLong("ts");
                JSONObject common = jsonObject.getJSONObject("common");
                String isNew = common.getString("is_new");
                // 当前日期
                String curDate = DateFormatUtil.tsToDate(ts);
                // 想想逻辑
                // 如果是新用户
                // 2024-08-16  10  1  10:00
                // 2024-08-16  10  1  12:00
                // 2024-08-17  10  0  10.00
                if ("1".equals(isNew)) {
                    if (value == null) {
                        firstLogin.update(curDate);
                    } else if (!value.equals(curDate)) {
                        common.put("is_new", 0);
                    }
                } else if ("0".equals(isNew)) {
                    // 认为昨天登录
                    firstLogin.update(DateFormatUtil.tsToDate(ts - 24 * 60 * 60 * 1000));
                } else {
                    // 留空
                }
                collector.collect(jsonObject);
            }
        });

        // 分流
        OutputTag<String> startTag = new OutputTag<String>("start", TypeInformation.of(String.class));
        OutputTag<String> errorTag = new OutputTag<String>("err", TypeInformation.of(String.class));
        OutputTag<String> displayTag = new OutputTag<String>("display", TypeInformation.of(String.class));
        OutputTag<String> actionTag = new OutputTag<String>("action", TypeInformation.of(String.class));
        SingleOutputStreamOperator<String> splitStream = isNewStream.process(new ProcessFunction<JSONObject, String>() {
            @Override
            public void processElement(JSONObject jsonObject, ProcessFunction<JSONObject, String>.Context context, Collector<String> collector) throws Exception {
                JSONObject err = jsonObject.getJSONObject("err");
                // 错误日志
                if (err != null) {
                    context.output(errorTag, jsonObject.toJSONString());
                    jsonObject.remove("err");
                }
                JSONObject start = jsonObject.getJSONObject("start");
                JSONObject page = jsonObject.getJSONObject("page");
                JSONObject common = jsonObject.getJSONObject("common");
                Long ts = jsonObject.getLong("ts");
                if (start != null) {
                    context.output(startTag, jsonObject.toJSONString());
                } else if (page != null) {
                    JSONArray displays = jsonObject.getJSONArray("displays");
                    // 曝光
                    if (displays != null) {
                        for (int i = 0; i < displays.size(); i++) {
                            //{{"item":"5","item_type":"sku_id","pos_id":4,"pos_seq":0},common:{},ts:12321312,"page":{}}
                            JSONObject display = displays.getJSONObject(i);
                            // 为了补充信息
                            display.put("common", common);
                            display.put("ts", ts);
                            display.put("page", page);
                            context.output(displayTag, display.toJSONString());
                        }
                        jsonObject.remove("displays");
                    }
                    // 动作
                    JSONArray actions = jsonObject.getJSONArray("actions");
                    if (actions != null) {
                        for (int i = 0; i < actions.size(); i++) {
                            //{{"item":"5","item_type":"sku_id","pos_id":4,"pos_seq":0},common:{},ts:12321312,"page":{}}
                            JSONObject action = actions.getJSONObject(i);
                            // 为了补充信息
                            action.put("common", common);
                            action.put("ts", ts);
                            action.put("page", page);
                            context.output(actionTag, action.toJSONString());
                        }
                        jsonObject.remove("actions");
                    }
                    // 主流
                    collector.collect(jsonObject.toJSONString());
                }
            }
        });

        // 取出侧流
        SideOutputDataStream<String> startStream = splitStream.getSideOutput(startTag);
        SideOutputDataStream<String> errorStream = splitStream.getSideOutput(errorTag);
        SideOutputDataStream<String> displayStream = splitStream.getSideOutput(displayTag);
        SideOutputDataStream<String> actionStream = splitStream.getSideOutput(actionTag);
        // 6、寫到kakfa
        startStream.print("start------------");
        errorStream.print("error---------");
        displayStream.print("display--------");
        actionStream.print("actionStream--------");
        splitStream.print("splitStream--------");

        // 写入Kafka
        startStream.sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_START));
        errorStream.sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ERR));
        displayStream.sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_DISPLAY));
        actionStream.sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ACTION));

        splitStream.sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_PAGE));
    }
}
